﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using OrderManager.Orders;
using OrderManager.ViewModels;

namespace OrderManager
{
    /// <summary>
    /// DownloadingWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DownloadingWindow : Window
    {
        internal List<Order> Orders { get; private set; }

        internal OrderManagerBase[] OrderManagers { set { this.models = value.Select(obj => new DownloadViewModel(obj)).ToArray(); } }

        internal OrderDownloadArgs DownloadArgs { get; set; }

        private DownloadViewModel[] models = null;
        private bool hasCancelClicked = false;

        public DownloadingWindow()
        {
            InitializeComponent();
            this.Orders = new List<Order>();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.lstOrderManagers.ItemsSource = this.models;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            foreach (var item in this.models)
            {
                item.Deattach();
                if (!this.hasCancelClicked)
                {
                    this.Orders.AddRange(item.Orders);
                }
            }
            this.DialogResult = !this.hasCancelClicked;

        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.hasCancelClicked = true;
            foreach (var item in this.models)
            {
                item.OrderManager.StopDownloadOrders();
            }
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            this.hasCancelClicked = false;
            foreach (var item in this.models)
            {
                item.OrderManager.StartDownloadOrders(this.DownloadArgs!=null ?this.DownloadArgs : new OrderDownloadArgs());
            }
        }
    }
}
